<?php

class AdminActivities{

	public static function precossRecievedPayment($data, $date=NULL){
		$date=$date==NULL ? date("Y-m-d") :$date;
		$details=Members::getPaymentDetails($data["mem_id"],$data["year_month"]);
		/*
		echo "<pre>";
			var_dump($data);
			var_dump($details);
		echo "</pre>";
		*/
		$paymentHistory=convertObjToArray(json_decode($details["monthly_payment_history"]));
		
		$paymentHistory[]=[
			"date"=>$data["dateOfPaymentRecieved"],
			"amountPayed"=>$data["amt_payed"],
			"paymentMode"=>$data["mode_of_payment"],
			"paymentType"=>$data["payment_type"],
			"note"=>$data["note"]
		];
		$totlAmtPayed=isset($details["total_amt_payed"]) ? $details["total_amt_payed"]+$data["amt_payed"] : $data["amt_payed"];
		//_var_dump($paymentHistory);
		$paymentHistory=json_encode($paymentHistory);
		$tdetails=Members::calculateAmountPayable($data["mem_id"],$date);
		$tdetails["totalAmtPayed"]=$totlAmtPayed;
		$tdetails["amountPayed"]=$data["amt_payed"];
		$data["transactionDetails"]=json_encode($tdetails);
		$transactionDetails=($details["transaction_details"]==NULL) || ($details["transaction_details"]=="") ? NULL : convertObjToArray(json_decode($details["transaction_details"]));
		//removing the 1st entry with ammount payed as zeron in the monthyly refresh script
		if($transactionDetails[0]["totalAmtPayed"]==0){
			$transactionDetails=NULL;
		}
		//$data["transactionDetails"]=$totlAmtPayed;
		$transactionDetails[]=convertObjToArray(json_decode($data["transactionDetails"]));	
		//_var_dump($transactionDetails);die();
		$transactionDetails=json_encode($transactionDetails);
		/*
		echo "<pre>";
			var_dump($data["transactionDetails"]);
			var_dump($transactionDetails);
		echo "</pre>";
		die();
		*/
		
		$totlAmtdue=$details["due_left"]-$data["amt_payed"] ;
		$updateArray=[
			"total_amt_payed"=>$totlAmtPayed,
			"transaction_details"=>$transactionDetails,
			"due_left"=>$totlAmtdue,
			"monthly_payment_history"=>$paymentHistory
		];
		$month_year=formatDate($date,"Ym");
		$whereString=" mem_id={$data["mem_id"]} AND  EXTRACT(YEAR_MONTH FROM applicable_from)='{$month_year}' ";
		$res= updateTable(PAYMENT_RECIEVED,$updateArray,$whereString);
		if(isset($res)){
			Self::updateTotalCollection($totlAmtPayed,"total_collection");
		}
		return $res;
		
		
	}
	
	public static function makePayment($data){
		$month_year=$data["dateOfPayment"];
		$data["dateOfPayment"]=validateDate($month_year) ? formatDate($month_year,"Ym") : $month_year;
		$sql=" 
			INSERT INTO 
				 ".PAYMENT_MADE." 
				(`id`, `payment_to`, `type`, `note`, `total_amt_payed`, `date_of_payment`)
			VALUES 
				(NULL, '{$data["payedTo"]}', '{$data['selectTypeOfPaymentMake']}', '{$data["note"]}', '{$data["amount"]}', '{$data["dateOfPayment"]}' )
		";
		
		$res= executeWriteQuery($sql);
		if(isset($res)){
			Self::updateTotalCollection($data["amount"],"total_expense");
		}
		return $res;
	}
	
	public static function getPaymentDetails($month_year){
		$month_year=validateDate($month_year) ? formatDate($month_year,"Ym") : $month_year;
		$sql="SELECT * FROM ".PAYMENT_MADE." WHERE EXTRACT(YEAR_MONTH FROM date_of_payment)='{$month_year}'";
		$res= convertObjToArray(executeReadQuery($sql));
		return  isset($res) ? $res : NULL;
	}
	
	public static function updateMemberDetails($data,$id){
		$whereString="id={$id}";
		return updateTable(MEMBERS,$data,$whereString);
	}
	public static function refreshPayment($id,$date){
		$paymentHistory=json_encode($paymentHistory);
		
		$details=Members::calculateAmountPayable($id,$date);
		$data["transactionDetails"]=json_encode($details);
		$transactionDetails=($details["transaction_details"]==NULL) || ($details["transaction_details"]=="") ? NULL : convertObjToArray(json_decode($details["transaction_details"]));
		$transactionDetails[]=convertObjToArray(json_decode($data["transactionDetails"]));	
		$transactionDetails=json_encode($transactionDetails);
		$paymentHistory=json_encode([]);
		$date=validateDate($date) ? formatDate($date,"Y-m-d") : NULL;
		
		$sql="INSERT INTO 
			`payment_recieved` 
			(`mem_id`, `amount_payable`, `total_amt_payed`, `transaction_details`, `due_left`, `monthly_payment_history`, `applicable_from`) 
			VALUES 
			({$id},{$details['total_amt_payable']},'0','{$transactionDetails}',{$details['total_amt_payable']},'{$paymentHistory}','{$date}')";
		executeWriteQuery($sql);
		//echo $sql;
	}
	
	public static function insertNewExtraCollection($data){
		$monthYear_arr=explode("-",$data['month_year']);
		$monthYear=implode("",$monthYear_arr);
		$date=date("Y-m-d");
		$sql="INSERT INTO `extra_collection`(`id`, `amt`, `reason`, `month_year`, `date`) VALUES (NULL,'{$data['amt']}', '{$data['reason']}', '{$monthYear}', '{$date}')";
		return executeWriteQuery($sql);
	}
	
	public static function updateTotalCollection($amt,$section){
		$amt=formatNumber(Self::getTotalCollection()[$section])+$amt;
		$sql="UPDATE ".TOTAL_FUND." SET {$section}={$amt} WHERE id=1";
		executeUpdateQuery($sql);
	}
	
	public static function getTotalCollection(){
		$sql="SELECT * FROM  ".TOTAL_FUND." WHERE id=1 ";
		$res=executeReadQuery($sql)[0];
		if(isset($res)){
			return $res;
		}else{
			$sql="INSERT INTO `total_fund`(`id`, `total_expense`, `total_collection`) VALUES (1,0,0)";
			executeWriteQuery($sql);
			return getTotalCollection();
		}
	}
}
?>